package com.itheima.tlias.aspect;

import com.itheima.tlias.annotation.LogOperation;
import com.itheima.tlias.mapper.LogMapper;
import com.itheima.tlias.utils.CurrentHolder;
import com.itheima.tlias.pojo.OperationLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * AOP切面类
 *
 * @Author mr.luo
 * @Date 12 4月 2025 20:17
 */
//@Aspect
//@Component
public class OperationLogAspect {

    @Autowired
    private LogMapper logMapper;

    // 环绕通知
    @Around("@annotation(log)")
    public Object around(ProceedingJoinPoint joinPoint, LogOperation log) throws Throwable {
        //形参列表中添加 LogOperation log 可以方便的获取注解里面的信息
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        // 执行方法
        Object result = joinPoint.proceed();
        // 当前时间
        long endTime = System.currentTimeMillis();
        // 耗时
        long costTime = endTime - startTime;

        // 构建日志对象
        OperationLog operateLog = new OperationLog();
        operateLog.setOperateEmpId(CurrentHolder.getCurrentId()); // 需要实现 getCurrentUserId 方法
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(joinPoint.getTarget().getClass().getName()); // 获取目标类名
        operateLog.setMethodName(joinPoint.getSignature().getName()); // 获取方法名
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs())); // 获取方法参数
        operateLog.setReturnValue(result.toString()); // 获取返回值
        operateLog.setCostTime(costTime); // 耗时

        // 插入日志
        logMapper.insert(operateLog);
        // 返回结果
        return result;
    }
}